package com.ecut.xzh.utils;


import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author XZH
 */
@Component
public class IpUtil {

    private static final String[] HEADERS_TO_CHECK = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "X-Real-IP"
    };

    /**
     * 获取用户真实IP地址。标准方法使用request.getRemoteAddr()可能返回代理或负载均衡器的IP地址。
     * 因此，该方法检查各种头部信息，以找到用户的真实IP地址。
     * 如果在'X-Forwarded-For'头部中找到多个IP地址，返回第一个非'unknown'的IP地址。
     *
     * @param request HttpServletRequest对象，包含客户端请求信息
     * @return 用户的真实IP地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        for (String header : HEADERS_TO_CHECK) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }


    /**
     * 判断给定的IP地址是否属于中国。
     *
     * @param ipAddress 要检查的IP地址
     * @return 如果IP地址属于中国，返回true，否则返回false
     */
    public static boolean isChineseIp(String ipAddress) {
        String apiUrl = "https://api.live.bilibili.com/client/v1/Ip/getInfoNew?ip=" + ipAddress;
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();


            JsonObject jsonObject = JsonParser.parseString(content.toString()).getAsJsonObject();
            JsonObject data = jsonObject.getAsJsonObject("data");
            if (data != null) {
                String country = data.get("country").getAsString();
                return "中国".equals(country) || "局域网".equals(country);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}


